package com.zatech.cgnci.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.enums.*;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.base.utils.*;
import com.zatech.cgnci.project.dto.ContractInvoiceUpmUpDTO;
import com.zatech.cgnci.project.dto.ReinsurancePremiumBillAddDTO;
import com.zatech.cgnci.project.dto.ReinsurancePremiumBillDTO;
import com.zatech.cgnci.project.entity.*;
import com.zatech.cgnci.project.mapper.*;
import com.zatech.cgnci.project.service.CgnciBusinessInsuranceService;
import com.zatech.cgnci.project.service.CgnciReinsuranceInfoService;
import com.zatech.cgnci.project.service.CgnciReinsurancePremiumBillService;
import com.zatech.cgnci.project.vo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 临分保费账单信息 服务实现类
 * </p>
 *
 * @author Generator
 * @since 2025-01-13
 */
@Service
public class CgnciReinsurancePremiumBillServiceImpl extends ServiceImpl<CgnciReinsurancePremiumBillMapper, CgnciReinsurancePremiumBillDO> implements CgnciReinsurancePremiumBillService {
    private final static String YYYYMMDD = "yyyyMMddHHmmssSSS";
    @Autowired
    private CgnciReinsurancePremiumDetailsMapper premiumDetailsMapper;
    @Autowired
    private CgnciReinsurancePaymentPlanMapper paymentPlanMapper;
    @Autowired
    private CgnciBusinessInsuranceService businessInsuranceService;
    @Autowired
    private CgnciReceiptPaymentBillsMapper billsMapper;
    @Autowired
    private CgnciProportionalLiabilityInvoiceMapper invoiceMapper;
    @Autowired
    private CgnciBusinessInsuranceMapper insuranceMapper;
    @Resource
    private CgnciReinsuranceInfoService cgnciReinsuranceInfoService;
    @Resource
    private CgnciClaimCaseTaskMapper claimCaseTaskMapper;
    @Override
    public IPage<ReinsurancePremiumBillVO> pageQuery(ReinsurancePremiumBillDTO queryDTO) {
        return this.baseMapper.pageBusinessInsurance(queryDTO.toPage(), queryDTO);
    }

    @Override
    @Transactional
    public void addContractInvoice(ReinsurancePremiumBillAddDTO addDTO) {
        UserEntity user = UserContext.getUser();
        CgnciReinsurancePremiumBillDO invoiceDO = ConvertUtils.convert(addDTO, CgnciReinsurancePremiumBillDO.class);
        StringBuilder invoiceNumber = new StringBuilder();
        if (Objects.isNull(invoiceDO.getId())) {
            invoiceDO.setStatus(BillStatusEnum.UNSETTLED.getCode());
            if (addDTO.getDirection().equals("1")) {
                invoiceNumber.append("SK");
            } else if (addDTO.getDirection().equals("2")) {
                invoiceNumber.append("FK");
            }
            invoiceNumber.append(DateUtils.dateElaborate());
            // 获取当前日期的开始时间和结束时间
            LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
            LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
            int count = this.baseMapper.selectCount(
                    new LambdaQueryWrapper<CgnciReinsurancePremiumBillDO>()
                            .between(CgnciReinsurancePremiumBillDO::getCreateTime,
                                    Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()),
                                    Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()))
            );
            invoiceNumber.append(String.format("%04d", count));
            invoiceDO.setInvoiceNumber(invoiceNumber.toString());
            invoiceDO.setCreateUser(user.getNameAndCode());
        } else {
            invoiceDO.setUpdateUser(user.getNameAndCode());

            Integer count =  billsMapper.selectCount(new LambdaQueryWrapper<CgnciReceiptPaymentBillsDO>()
                    .eq(CgnciReceiptPaymentBillsDO::getInvoiceNumber,addDTO.getInvoiceNumber())
                    .ne(CgnciReceiptPaymentBillsDO::getStatus,BillStatusEnum.UNSETTLED.getCode()));
            if(count>0){
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "收付费已关联，不允许修改");
            }
        }
        premiumDetailsMapper.delete(new LambdaQueryWrapper<CgnciReinsurancePremiumDetailsDO>().eq(CgnciReinsurancePremiumDetailsDO::getInvoiceNumber, invoiceDO.getInvoiceNumber()));
        paymentPlanMapper.delete(new LambdaQueryWrapper<CgnciReinsurancePaymentPlanDO>().eq(CgnciReinsurancePaymentPlanDO::getInvoiceNumber, invoiceDO.getInvoiceNumber()));
        for (CgnciReinsurancePremiumDetailsDO detailsDO : addDTO.getPremiumDetailsDOS()) {
            //账单明细
            detailsDO.setInvoiceNumber(invoiceNumber.toString());
            if(StringUtils.isEmpty(invoiceNumber.toString())){
                detailsDO.setInvoiceNumber(addDTO.getInvoiceNumber());
            }
            detailsDO.setCreateUser(user.getNameAndCode());
            detailsDO.setCreateTime(new Date());
            premiumDetailsMapper.insert(detailsDO);
        }
        for (CgnciReinsurancePaymentPlanDO paymentPlanDO : addDTO.getPaymentPlanDOS()) {
            paymentPlanDO.setCreateUser(user.getNameAndCode());
            paymentPlanDO.setCreateTime(new Date());
            paymentPlanDO.setInvoiceNumber(invoiceNumber.toString());
            if(StringUtils.isEmpty(invoiceNumber.toString())){
                paymentPlanDO.setInvoiceNumber(addDTO.getInvoiceNumber());
            }
            paymentPlanMapper.insert(paymentPlanDO);
            if (Objects.isNull(invoiceDO.getId())) {
                CgnciReceiptPaymentBillsDO paymentBillsDO = ConvertUtils.convert(invoiceDO,CgnciReceiptPaymentBillsDO.class);
                paymentBillsDO.setAmount(paymentPlanDO.getAmountPayable());
                paymentBillsDO.setId(null);
                paymentBillsDO.setBillType(BillTypeEnum.REINSURANCE_PREMIUM_BILL.getCode());
                paymentBillsDO.setPaymentPeriod(paymentPlanDO.getPaymentPeriod());
                paymentBillsDO.setCreateUser(user.getNameAndCode());
                paymentBillsDO.setCreateTime(new Date());
                billsMapper.insert(paymentBillsDO);
            }else{
                CgnciReceiptPaymentBillsDO paymentBillsDO = ConvertUtils.convert(invoiceDO,CgnciReceiptPaymentBillsDO.class);
                paymentBillsDO.setAmount(paymentPlanDO.getAmountPayable());
                paymentBillsDO.setId(null);
                paymentBillsDO.setBillType(BillTypeEnum.REINSURANCE_PREMIUM_BILL.getCode());
                paymentBillsDO.setPaymentPeriod(paymentPlanDO.getPaymentPeriod());
                //更新收付费账单表
                billsMapper.update(paymentBillsDO,new LambdaQueryWrapper<CgnciReceiptPaymentBillsDO>().eq(CgnciReceiptPaymentBillsDO::getInvoiceNumber,invoiceDO.getInvoiceNumber())
                        .eq(CgnciReceiptPaymentBillsDO::getPaymentPeriod,paymentPlanDO.getPaymentPeriod()));
            }
        }
        this.saveOrUpdate(invoiceDO);
    }

    @Override
    public ReinsurancePremiumBillDetailsVO getDetails(Long id) {
        CgnciReinsurancePremiumBillDO invoiceDO = this.baseMapper.selectById(id);
        ReinsurancePremiumBillDetailsVO detailsVO = ConvertUtils.convert(invoiceDO, ReinsurancePremiumBillDetailsVO.class);
        List<CgnciReinsurancePremiumDetailsDO> detailsDOList = premiumDetailsMapper.selectList(new LambdaUpdateWrapper<CgnciReinsurancePremiumDetailsDO>()
                .eq(CgnciReinsurancePremiumDetailsDO::getInvoiceNumber, invoiceDO.getInvoiceNumber()));
        List<CgnciReinsurancePaymentPlanDO> paymentPlanDOS = paymentPlanMapper.selectList(new LambdaUpdateWrapper<CgnciReinsurancePaymentPlanDO>()
                .eq(CgnciReinsurancePaymentPlanDO::getInvoiceNumber, invoiceDO.getInvoiceNumber())
                .orderByDesc(CgnciReinsurancePaymentPlanDO::getPaymentPeriod));
        detailsVO.setPremiumDetailsDOS(detailsDOList);
        detailsVO.setPaymentPlanDOS(paymentPlanDOS);
        return detailsVO;
    }

    @Override
    public void updateUpm(ContractInvoiceUpmUpDTO updateDTO) {
        CgnciReinsurancePremiumBillDO cgnciContractInvoiceDO = CgnciReinsurancePremiumBillDO.builder()
                .id(updateDTO.getId())
                .upmNumber(updateDTO.getUpmNumber())
                .postingDate(updateDTO.getPostingDate())
                .updateUser(updateDTO.getUpdateUser())
                .updateTime(new Date())
                .build();
        this.baseMapper.updateById(cgnciContractInvoiceDO);
    }

    @Override
    @Transactional
    public void delete(Long id, String invoiceNumber) {
        Integer count =  billsMapper.selectCount(new LambdaQueryWrapper<CgnciReceiptPaymentBillsDO>()
                .eq(CgnciReceiptPaymentBillsDO::getInvoiceNumber,invoiceNumber)
                .ne(CgnciReceiptPaymentBillsDO::getStatus,BillStatusEnum.UNSETTLED.getCode()));
        if(count>0){
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "收付费已关联，不允许删除");
        }
        //删除收付费管理数据
        billsMapper.delete(new LambdaQueryWrapper<CgnciReceiptPaymentBillsDO>()
                .eq(CgnciReceiptPaymentBillsDO::getInvoiceNumber,invoiceNumber));
        this.baseMapper.deleteById(id);
        // 构建 LambdaQueryWrapper 并设置删除条件
        LambdaQueryWrapper<CgnciReinsurancePremiumDetailsDO> wrapper = new LambdaQueryWrapper<CgnciReinsurancePremiumDetailsDO>()
                .eq(CgnciReinsurancePremiumDetailsDO::getInvoiceNumber, invoiceNumber);
        premiumDetailsMapper.delete(wrapper);

        LambdaQueryWrapper<CgnciReinsurancePaymentPlanDO> wrapperPlan = new LambdaQueryWrapper<CgnciReinsurancePaymentPlanDO>()
                .eq(CgnciReinsurancePaymentPlanDO::getInvoiceNumber, invoiceNumber);
        paymentPlanMapper.delete(wrapperPlan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateDisengagement(Long insuranceId) {
        CgnciBusinessInsuranceMainVO mainVO = businessInsuranceService.detail(insuranceId, "4");
        //基本信息
        CgnciBusinessInsuranceVO businessInsuranceVO = mainVO.getBusinessInsuranceVO();
        //直保信息
        CgnciDirectInsuranceVO directInsuranceVO= mainVO.getDirectInsuranceVO();
        Map<String, CgnciDirectInsuranceRiskVO> riskSubTypeCodeMap = directInsuranceVO.getInsuranceRisks().stream()
                .collect(Collectors.toMap(
                        CgnciDirectInsuranceRiskVO::getRiskSubTypeCode,
                        paymentPlan -> paymentPlan
                ));
        CgnciReinsuranceInfoVO infoVO = mainVO.getLfDivideOutVO();
        if (Objects.isNull(infoVO) || CollectionUtils.isEmpty(infoVO.getReinsurers())) {
            return;
        }
        // 获取当前日期的开始时间和结束时间
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
        int count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<CgnciReinsurancePremiumBillDO>()
                        .between(CgnciReinsurancePremiumBillDO::getCreateTime,
                                Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()),
                                Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()))
        );
        List<CgnciReinsurerVO> reinsurers = infoVO.getReinsurers();
        for (CgnciReinsurerVO reinsurerVO : reinsurers) {
            for (CgnciReinsurerRiskVO riskVO : reinsurerVO.getRisks()) {
                for(CgnciReinsurerRiskInsuredVO insuredVO:riskVO.getRiskInsureds()) {
                    for (CgnciReinsurerRiskLayerVO riskLayerVO : insuredVO.getRiskLayers()) {
                        StringBuilder invoiceNumber = new StringBuilder();
                        invoiceNumber.append("FK");
                        invoiceNumber.append(DateUtils.formatDate(new Date(), YYYYMMDD));
                        invoiceNumber.append(String.format("%04d", count));
                        count++;
                        BigDecimal checkAmount = riskLayerVO.getGrossPremium().subtract(riskLayerVO.getCommission());
                        String direction = "1";
                        if (checkAmount.signum() < 0) {
                            direction = "2";
                        }
                        CgnciDirectInsuranceRiskVO detailVO = riskSubTypeCodeMap.get(riskVO.getRiskSubTypeCode());
                        CgnciReinsurancePremiumBillDO cgnciContractInvoiceDO = CgnciReinsurancePremiumBillDO.builder()
                                //"保单号"
                                .policyNumber(businessInsuranceVO.getBusinessNo())
                                //"合约类型 1分入，2分出
                                .contractType("2")
                                //.dueDate()
                                .billingCycle(DateUtils.formatDate(businessInsuranceVO.getStartDate(), DateUtils.FORMAT_3) + "-" + DateUtils.formatDate(businessInsuranceVO.getStartDate(), DateUtils.FORMAT_3))
                                .postingDate(businessInsuranceVO.getEntryDate())
                                //再保分出人"
                                .cedingCompany("CGN Captive Insurance Limited")
                                .receiver(reinsurerVO.getReinsurerName())
                                //项目名称
                                .projectName(businessInsuranceVO.getProjectName())
                                //接收人份额
                                .yourShare(riskLayerVO.getCededRatio())
                                //原始保额
                                .maxCompensation(Objects.nonNull(detailVO) ? detailVO.getDetails().stream()
                                        .map(risk -> BeanUtils.sumBigDecimalProperty(detailVO.getDetails(), CgnciDirectInsuranceDetailVO::getMaxCompensation))
                                        .reduce(BigDecimal.ZERO, BigDecimal::add) : new BigDecimal(0))
                                //再保经纪人
                                .reinsuranceBroker(infoVO.getBroker())

                                .startDate(businessInsuranceVO.getStartDate())

                                .endDate(businessInsuranceVO.getEndDate())
                                //保险期限"
                                .policyTerm(businessInsuranceVO.getInsuranceDays().toString())
                                //再保手续费率
                                .procedureRate(reinsurerVO.getProcedureRate())
                                //险种
                                .policyType(riskVO.getRiskSubTypeCode())
                                //账单编号
                                .invoiceNumber(invoiceNumber.toString())
                                //账单币种
                                .currency(businessInsuranceVO.getCurrency())
                                //汇率
                                .fxRate(businessInsuranceVO.getExchangeRate())
                                //账单接收人
                                .billRecipient(reinsurerVO.getReinsurerName())
                                .createUser("System")
                                //收付方向
                                .direction(direction)
                                //总金额
                                .collectAmount(riskLayerVO.getGrossPremium().add(riskLayerVO.getCommission()))
                                //账单状态
                                .status("01").build();
                        this.baseMapper.insert(cgnciContractInvoiceDO);
                        CgnciReinsurancePremiumDetailsDO detailsDO = new CgnciReinsurancePremiumDetailsDO();
                        detailsDO.setInvoiceNumber(invoiceNumber.toString());
                        detailsDO.setFeeType(FeeTypeEnum.PREMIUM.getCode());
                        detailsDO.setPaymentType(PaymentTypeEnum.CHARGE.getCode());
                        detailsDO.setAmount(riskLayerVO.getNetPremium());
                        detailsDO.setCreateUser("System");
                        //账单明细
                        premiumDetailsMapper.insert(detailsDO);
                        CgnciReinsurancePremiumDetailsDO detailsDO2 = new CgnciReinsurancePremiumDetailsDO();
                        detailsDO2.setInvoiceNumber(invoiceNumber.toString());
                        detailsDO2.setFeeType(FeeTypeEnum.HANDLING_CHARGE.getCode());
                        detailsDO2.setPaymentType(PaymentTypeEnum.PAY.getCode());
                        detailsDO2.setAmount(riskLayerVO.getCommission());
                        detailsDO.setCreateUser("System");
                        //账单明细
                        premiumDetailsMapper.insert(detailsDO2);
                        if (reinsurerVO.getRisks().size() == 1 && riskVO.getRiskInsureds().size() == 1&&riskVO.getRiskInsureds().get(0).getRiskLayers().size()==1) {
                            for (CgnciPaymentScheduleVO scheduleVO : reinsurerVO.getPayments()) {
                                CgnciReinsurancePaymentPlanDO paymentPlanDO = new CgnciReinsurancePaymentPlanDO();
                                paymentPlanDO.setInvoiceNumber(invoiceNumber.toString());
                                paymentPlanDO.setPaymentPeriod(scheduleVO.getPaymentPeriod());
                                paymentPlanDO.setAmountPayable(scheduleVO.getPremiumExclTax());
                                paymentPlanDO.setPaymentDeadline(DateUtils.formatDate(scheduleVO.getPaymentEndDate(), DateUtils.FORMAT_3));
                                paymentPlanDO.setCreateUser("System");
                                paymentPlanMapper.insert(paymentPlanDO);

                                CgnciReceiptPaymentBillsDO paymentBillsDO = ConvertUtils.convert(cgnciContractInvoiceDO, CgnciReceiptPaymentBillsDO.class);
                                paymentBillsDO.setAmount(paymentPlanDO.getAmountPayable());
                                paymentBillsDO.setId(null);
                                paymentBillsDO.setBillType(BillTypeEnum.REINSURANCE_PREMIUM_BILL.getCode());
                                paymentBillsDO.setPaymentPeriod(paymentPlanDO.getPaymentPeriod());
                                billsMapper.insert(paymentBillsDO);
                            }
                        } else {
                            for(CgnciReinsurerRiskInsuredVO riskInsuredVO:riskVO.getRiskInsureds()) {
                                int risks = reinsurerVO.getRisks().size() + riskInsuredVO.getRiskLayers().size() - 1;
                                for (CgnciPaymentScheduleVO scheduleVO : reinsurerVO.getPayments()) {
                                    CgnciReinsurancePaymentPlanDO paymentPlanDO = new CgnciReinsurancePaymentPlanDO();
                                    paymentPlanDO.setInvoiceNumber(invoiceNumber.toString());
                                    paymentPlanDO.setPaymentPeriod(scheduleVO.getPaymentPeriod());
                                    paymentPlanDO.setAmountPayable(scheduleVO.getPremiumExclTax().divide(new BigDecimal(risks), 2, RoundingMode.HALF_UP));
                                    paymentPlanDO.setPaymentDeadline(DateUtils.formatDate(scheduleVO.getPaymentEndDate(), DateUtils.FORMAT_3));
                                    paymentPlanDO.setCreateUser("System");
                                    paymentPlanMapper.insert(paymentPlanDO);

                                    CgnciReceiptPaymentBillsDO paymentBillsDO = ConvertUtils.convert(cgnciContractInvoiceDO, CgnciReceiptPaymentBillsDO.class);
                                    paymentBillsDO.setAmount(scheduleVO.getPremiumExclTax().divide(new BigDecimal(risks), 2, RoundingMode.HALF_UP));
                                    paymentBillsDO.setId(null);
                                    paymentBillsDO.setBillType(BillTypeEnum.REINSURANCE_PREMIUM_BILL.getCode());
                                    paymentBillsDO.setPaymentPeriod(paymentPlanDO.getPaymentPeriod());
                                    billsMapper.insert(paymentBillsDO);
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    @Override
    public CgnciBillStatusVO queryBillStatus(String policyNumber) {
        CgnciBillStatusVO cgnciBillStatusVO = new CgnciBillStatusVO();
        List<CgnciReceiptPaymentBillsDO> billsDOS = billsMapper.selectList(new LambdaQueryWrapper<CgnciReceiptPaymentBillsDO>()
                .eq(CgnciReceiptPaymentBillsDO::getPolicyNumber,policyNumber));
        if(CollectionUtils.isNotEmpty(billsDOS)) {
            cgnciBillStatusVO.setBillVOList(ConvertUtils.convert(billsDOS, ReinsurancePremiumBillVO.class));
        }
        List<CgnciProportionalLiabilityInvoiceDO> invoiceDOS =  invoiceMapper.selectList(new LambdaQueryWrapper<CgnciProportionalLiabilityInvoiceDO>()
                .eq(CgnciProportionalLiabilityInvoiceDO::getPolicyNumber,policyNumber));
        if(CollectionUtils.isNotEmpty(invoiceDOS)) {
            cgnciBillStatusVO.setInvoiceVOList(ConvertUtils.convert(invoiceDOS, ProportionalLiabilityInvoiceVO.class));
        }
        return cgnciBillStatusVO;
    }

    @Override
    public CgnciBillMainVO getPolicyInfo(String policyNumber) {
        CgnciBillMainVO  mainVO = new CgnciBillMainVO();
        if (VerifyUtils.isEmpty(policyNumber)) {
            return null;
        }
        LambdaQueryWrapper<CgnciBusinessInsuranceDO> query = new LambdaQueryWrapper<CgnciBusinessInsuranceDO>()
                .eq(CgnciBusinessInsuranceDO::getBusinessNo, policyNumber)
                .eq(CgnciBusinessInsuranceDO::getStatus,"3")
                .eq(CgnciBusinessInsuranceDO::getIsEffective, "1")
                .eq(CgnciBusinessInsuranceDO::getIsMirror, "0");
        CgnciBusinessInsuranceDO cgnciBusinessInsuranceDO = insuranceMapper.selectOne(query);
        if (VerifyUtils.isEmpty(cgnciBusinessInsuranceDO)) {
            return null;
        }
        CgnciBusinessInsuranceVO businessInsuranceVO = ConvertUtils.convert(cgnciBusinessInsuranceDO, CgnciBusinessInsuranceVO.class);
        mainVO.setBusinessInsuranceVO(businessInsuranceVO);
        mainVO.setDivideInVO(cgnciReinsuranceInfoService.getDivideInReinsuranceByInsuranceId(cgnciBusinessInsuranceDO.getInsuranceId()));
        List<String> taskTypes = new ArrayList<>();
        taskTypes.add(ClaimTaskTypeEnum.PREPAY.getCode());
        taskTypes.add(ClaimTaskTypeEnum.CLOSE.getCode());
        List<CgnciClaimCaseTaskDO> claimCaseTaskDOS = claimCaseTaskMapper.selectList(new LambdaQueryWrapper<CgnciClaimCaseTaskDO>()
                .in(CgnciClaimCaseTaskDO::getTaskType,taskTypes)
                .eq(CgnciClaimCaseTaskDO::getTaskStatus,ClaimTaskStatusEnum.DONE.getCode()));
        mainVO.setCaseTaskVOList(ConvertUtils.convert(claimCaseTaskDOS, CgnciClaimCaseTaskVO.class));
        return mainVO;
    }

    @Override
    public Boolean verifyPremium(String policyNo) {
       Integer count =  this.baseMapper.selectCount(new LambdaQueryWrapper<CgnciReinsurancePremiumBillDO>()
                .eq(CgnciReinsurancePremiumBillDO::getPolicyNumber,policyNo)
                .eq(CgnciReinsurancePremiumBillDO::getDirection,DirectionEnum.COLLECTION.getCode())
                .ne(CgnciReinsurancePremiumBillDO::getStatus,BillStatusEnum.SETTLED.getCode()));
       return count>0;
    }

    @Override
    public String queryPremium(String policyNo) {
        List<CgnciReinsurancePremiumBillDO> premiumBillDOS=  this.baseMapper.selectList(new LambdaQueryWrapper<CgnciReinsurancePremiumBillDO>()
                .eq(CgnciReinsurancePremiumBillDO::getPolicyNumber,policyNo)
                .eq(CgnciReinsurancePremiumBillDO::getDirection,DirectionEnum.COLLECTION.getCode()));
        if(CollectionUtils.isEmpty(premiumBillDOS)){
            return null;
        }
        CgnciReinsurancePremiumBillDO premiumBillDO = premiumBillDOS.get(0);
        List<CgnciReinsurancePaymentPlanDO> paymentPlanDOS = paymentPlanMapper.selectList(new LambdaUpdateWrapper<CgnciReinsurancePaymentPlanDO>()
                .eq(CgnciReinsurancePaymentPlanDO::getInvoiceNumber, premiumBillDO.getInvoiceNumber()));
        return paymentPlanDOS.stream()
                .map(ds -> ds.getPaymentPeriod() + "期-" + BillStatusEnum.getEnumByCode(premiumBillDO.getStatus()).getDescr())
                .collect(Collectors.joining(","));
    }

}
